package com.atguigu.controller;

import com.atguigu.entity.CartInfo;
import com.atguigu.result.RetVal;
import com.atguigu.service.CartInfoService;
import com.atguigu.util.AuthContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/cart/")
public class CartController {
    @Autowired
    private CartInfoService cartInfoService;

    /**
     * @RequestParam 接受 blogs?blogId=1
     * @PathVariable，例如/blogs/1
     *
     */
    //1.添加购物车
    @PostMapping("addToCart/{skuId}/{skuNum}")
    public RetVal addToCart(@RequestParam Long skuId, @RequestParam Integer skuNum, HttpServletRequest request){
        //拿取用户id
        String userId = AuthContextHolder.getUserId(request);
        //如果没有登录，userId没有值
        if(StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart(userId,skuId,skuNum);
        return RetVal.ok();
    }
    //2.购物车列表展示
    @GetMapping("getCartList")
    public RetVal getCartList(HttpServletRequest request){
        //拿取用户id
        String userId = AuthContextHolder.getUserId(request);
        //拿取临时用户id
        String userTempId=AuthContextHolder.getUserTempId(request);
        List<CartInfo> cartInfoList=cartInfoService.getCartList(userId,userTempId);
        return RetVal.ok(cartInfoList);
    }

    //http://api.gmall.com/cart/checkCart/24/0
    //3.商品的选中
    @GetMapping("checkCart/{skuId}/{isChecked}")
    public RetVal checkCart(@PathVariable Long skuId,@PathVariable Integer isChecked,HttpServletRequest request){
        //拿取用户id
        String userId = AuthContextHolder.getUserId(request);
        //如果没有登录，userId没有值
        if(StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.checkCart(userId,skuId,isChecked);
        return RetVal.ok();
    }
    //4.商品购物车删除 deleteCart/24
    @DeleteMapping("deleteCart/{skuId}")
    public RetVal deleteCart(@PathVariable Long skuId,HttpServletRequest request){
        //拿取用户id
        String userId = AuthContextHolder.getUserId(request);
        //如果没有登录，userId没有值
        if(StringUtils.isEmpty(userId)){
            userId=AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.deleteCart(userId,skuId);
        return RetVal.ok();
    }

    //5.查询选中的商品信息
    @GetMapping("getSelectedProduct/{userId}")
    public List<CartInfo> getSelectedProduct(@PathVariable String userId){
        return cartInfoService.getSelectedProduct(userId);
    }
    //6.从数据库中查询购物车缓存信息
    @GetMapping("queryFromDbToRedis/{userId}")
    public List<CartInfo> queryFromDbToRedis(@PathVariable String userId){
        return cartInfoService.queryFromDbToRedis(userId);
    }
}
